<?php

namespace app\common\model\sms;

use app\common\library\sms\Driver as SmsDriver;
use app\common\model\BaseModel;
use app\common\model\settings\Setting as SettingModel;
use app\common\model\supplier\Supplier;
use think\facade\Db;


/**
 * @author libh
 * @date 2024-5-14
 * @description 实现发送短信绑定商户，并校验商户短信条数
 */
class Sms extends BaseModel
{
    protected $name = 'sms';
    protected $pk = 'sms_id';
    private $deadline = 300;	//验证码失效时间
    private $ip_count = 5; 	//同ip发送短信次数限制
    private $day_count = 5;

    public function sendSms($mobile, $template_code, $sence, $send_data, $shop_supplier_id = 0, $app_id = 0)
    {
//        if (empty($mobile)) {
//            $this->error = '手机号码不能为空';
//            return false;
//        }

        if(!preg_match("/^1[23456789]\d{9}$/", $mobile)){
            $this->error = '手机号码格式有误';
            return false;
        }
        //登录需要验证
        if($sence == 'login'){
            $result = $this -> sendCheck($mobile);
            if($result['success'] == false){
                $this->error = $result['msg'];
                return false;
            }
            $env = "development";
            //调用发送短信方法
            if($env == "development"){ //测试环境不发送短信
                $code = rand(100000,999999);
                $data['success'] = true;
                $data['msg'] = '验证码'.$code.'(测试环境)';

                $this->save([
                    'mobile' => $mobile,
                    'code' => $send_data["code"] ?? $template_code,
                    'sence' => $sence,
                    'app_id' => $app_id > 0 ? $app_id : self::$app_id,
                    'shop_supplier_id' => $shop_supplier_id,
                    'ip' => request()->ip(),
                    'app_status' => 'development'
                ]);

                return $data;
            }
        }

        // 20240516 Mr.Z 未启用前暂时屏蔽
        // if ($shop_supplier_id > 0) {
        //     $supplier = Supplier::detail($shop_supplier_id);
        //     if (empty($supplier) || $supplier["is_delete"] == 0 || $supplier["is_recycle"] != 0) {
        //         $this->error = '商家不存在';
        //         return false;
        //     }
        //     if ($supplier["is_audit"] != 1) {
        //         $this->error = '商家状态异常';
        //         return false;
        //     }
        //     if ($supplier["sms_num"] < 1) {
        //         $this->error = '商家短信可以条数为0';
        //         return false;
        //     }
        // }

        $smsConfig = SettingModel::getItem('sms', $app_id > 0 ? $app_id : self::$app_id);
        $SmsDriver = new SmsDriver($smsConfig);
        $flag = $SmsDriver->sendSms($mobile, $template_code, $send_data);
        if ($flag) {
            $this->save([
                'mobile' => $mobile,
                'code' => $send_data["code"] ?? $template_code,
                'sence' => $sence,
                'app_id' => $app_id > 0 ? $app_id : self::$app_id,
                'shop_supplier_id' => $shop_supplier_id,
                'ip' => request()->ip(),
                'app_status' => 'production'
            ]);
            // 20240516 Mr.Z 未启用前暂时屏蔽
            // if (!empty($supplier)) {
            //     $supplier->save(["sms_num" => $supplier['sms_num'] - 1]);
            // }
            return true;
        }
        $this->error = $SmsDriver->getError();
        return false;
    }



    //验证短信验证码
    public function verify($mobile,$code){
        return true;

    }

    /**
     * 发送验证，检查是否还有有效验证码
     * sendCheck
     * @param $mobile
     * array
     * @return array
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @Author kevin
     * @date 2024/5/23 10:17
     */

    private function sendCheck($mobile){
        $start_time = strtotime(date("Y-m-d"));
        $end_time = strtotime(date('Y-m-d', strtotime('+1 day')));
        $ip = request() -> ip();

        //同ip发送验证码次数查询
        $ip_count_map[] = ['ip','=',$ip];
        $ip_count_map[] = ['create_time','>=',$start_time];
        $ip_count_map[] = ['create_time','<=',$end_time];

        $ip_count = $this -> where($ip_count_map) -> count();

        if($ip_count > $this -> ip_count){
            $data['success'] = false;
            $data['msg'] = '此IP验证码发送次数过多，请明天再尝试!';
            return $data;
        }

        //有效验证码查询
        $map[] = ['mobile','=',$mobile];
        $map[] = ['state','=',0];
        $map[] = ['create_time','between time',[$start_time,$end_time]];

        $log = $this -> where($map) -> order('create_time desc') -> find();
        $count = $this -> where($map) -> order('create_time desc') -> count();

        if($count == 0){
            $data['success'] = true;
            return $data;
        }
        if($count >= $this -> day_count){
            $data['success'] = false;
            $data['msg'] = '您的验证码发送次数过多，请明天再尝试';
            return $data;
        }
        if($log['create_time'] > time() - $this -> deadline){
            $data['success'] = false;
            $data['msg'] = '验证码仍然有效，请勿重复获取';
            return $data;
        }

        $data['success'] = true;
        return $data;
    }


}